<template>
  <el-row :gutter="30">
    <!-- 商品图片 -->
    <el-col :span="12">
      <img
        :src="product.image"
        alt="商品图片"
        style="width: 100%; height: 400px; object-fit: contain; border: 1px solid #eee;"
      >
    </el-col>
    <!-- 商品信息 -->
    <el-col :span="12">
      <h2 style="margin-bottom: 20px;">{{ product.name }}</h2>
      <p style="color: #f56c6c; font-size: 24px; margin-bottom: 30px;">¥{{ product.price }}</p>

      <el-divider content-position="left">商品描述</el-divider>
      <p style="line-height: 1.8; margin: 20px 0;">{{ product.description }}</p>

      <el-divider content-position="left">库存</el-divider>
      <p style="margin: 20px 0;">当前库存：{{ product.stock }} 件</p>

      <el-button
        type="primary"
        size="large"
        @click="addToCart"
        :disabled="!store.user"
      >
        {{ store.user ? '加入购物车' : '请先登录' }}
      </el-button>
    </el-col>
  </el-row>
</template>

<script setup>
import { defineEmits } from 'vue'
import { useStore } from '../store'
import { ElMessage } from 'element-plus'

// 接收父组件传入的商品数据
const props = defineProps({
  product: {
    type: Object,
    required: true
  }
})

const store = useStore()
const emit = defineEmits(['cart-updated']) // 仅此处声明

// 加入购物车逻辑
const addToCart = async () => {
  if (!store.user) {
    ElMessage.warning('请先登录')
    return
  }
  await store.addToCart(props.product)
  ElMessage.success('已加入购物车！')
  emit('cart-updated') // 通知父组件购物车更新
}
</script>
